import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '@/api/user'
import Cookies from 'js-cookie'

export const useUserStore = defineStore('user', () => {
  // 页面加载时自动从localStorage恢复用户信息
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || null)
  const token = ref(localStorage.getItem('token') || '')

  // 自动恢复 userInfo（防止页面刷新后 userInfo 丢失）
  if (!userInfo.value && localStorage.getItem('userInfo')) {
    userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
  }

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  // 设置用户信息，并持久化到localStorage
  const setUserInfo = (info) => {
    // 兼容后端 userId 字段
    if (info && info.userId && !info.id) {
      info.id = info.userId
    }
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }

  // 登录
  const login = async (loginData) => {
    try {
      const response = await userApi.login(loginData)
      if (response.code === 200) {
        setToken(response.data.token)
        setUserInfo(response.data)
        return { success: true, data: response.data }
      }
      return { success: false, message: response.message }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  // 注册
  const register = async (registerData) => {
    try {
      const response = await userApi.register(registerData)
      if (response.code === 200) {
        return { success: true, data: response.data }
      }
      return { success: false, message: response.message }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  // 获取用户信息
  const getUserInfo = async (userId) => {
    try {
      const response = await userApi.getUserInfo(userId)
      if (response.code === 200) {
        setUserInfo(response.data)
        return { success: true, data: response.data }
      }
      return { success: false, message: response.message }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  // 登出
  const logout = () => {
    clearToken()
    userInfo.value = null
    localStorage.removeItem('userInfo')
  }

  return {
    userInfo,
    token,
    login,
    register,
    getUserInfo,
    logout,
    setToken,
    clearToken,
    setUserInfo
  }
}) 